package com.speakglobe.jms;

import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.speakglobe.admin.service.AdminService;
import com.speakglobe.security.model.User;
import com.speakglobe.security.service.UserDetailsService;

public class EmailServiceImpl implements EmailService {
	
	private UserDetailsService userDetailsService;
	private AdminService adminService;
	
	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	@Override
	public void sendEmail(String fromEmail, List<String> recipientEmails,
			List<String> copiedRecipientEmails,
			List<String> blindRecipientEmails, String subjectLine,
			String bodyText, String htmlText, List attachments,
			List inLineAttachments, boolean isHtml) throws MessagingException {
		
		boolean hasAtLeastOneRecipient = false;
		String smtpHost = adminService.getValueForSystemProperty("smtpHost");
		
		if(smtpHost != null && smtpHost.length() > 0) {
			JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
			mailSender.setHost(smtpHost);
			
			MimeMessage email = mailSender.createMimeMessage();
			boolean multipart = true;
			
			MimeMessageHelper helper = new MimeMessageHelper(email, multipart, "UTF-8");
    		helper.setFrom(fromEmail);
    		
    		if(recipientEmails != null && recipientEmails.size() > 0) {
    			hasAtLeastOneRecipient = true;
    			String[] recipientEmailArr = (String[]) recipientEmails.toArray(new String[1]);
    			helper.setTo(recipientEmailArr);
    		}
    		
    		if(copiedRecipientEmails != null && copiedRecipientEmails.size() > 0) {
    			hasAtLeastOneRecipient = true;
    			String[] copiedRecipientEmailArr = (String[]) copiedRecipientEmails
    			.toArray(new String[1]);
    			helper.setCc(copiedRecipientEmailArr);
    		}

    		if(blindRecipientEmails != null && blindRecipientEmails.size() > 0) {
    			hasAtLeastOneRecipient = true;
    			String[] blindRecipientEmailArr = (String[]) blindRecipientEmails
    			.toArray(new String[1]);
    			helper.setBcc(blindRecipientEmailArr);
    		}

    		if(subjectLine != null && subjectLine.length() > 0) {
    			helper.setSubject(subjectLine);
    		}

    		if(htmlText != null && htmlText.length() > 0) {
    			helper.setText(htmlText, isHtml);
    		} else {
    			if(bodyText != null && bodyText.length() > 0) {
    				helper.setText(bodyText);
    			}
    		}
    		
    		if(hasAtLeastOneRecipient) {
    			mailSender.send(email);
    		} else {
    		}
		}

	}

	@Override
	public Boolean sendPasswordRequestEmail(String emailAddress, User user,
			ServletContext ctx) throws Exception {
		List<String> recipientEmails = new ArrayList<String>();    	
    	recipientEmails.add(emailAddress);    	
    	
    	try {    		
    		InputStream is = ctx.getResourceAsStream("/template/PASSWORD_RETRIEVE.html");

    		String emailTemplate = convertStreamToString(is);
    		
    		emailTemplate = emailTemplate.replace("@@FIRST_NAME", user.getUsername()).replace("@@LAST_NAME",user.getUsername())
    						.replace("@@USER_NAME", user.getUsername()).replace("@@PASSWORD", user.getDecryptPassword());
    		    		
    		sendEmail("cust_service@epmonline.com", recipientEmails, null, null, "SourcingBench: User ID and Password Request",
    				null, emailTemplate, null, null, true);
    		
    		recipientEmails.clear();

    	} catch(Exception e) {
    		return false;
    	}
    	
    	return true;
	}

	@Override
	public Boolean sendSupportEmail(String from, String emailSupport,
			String userName, ServletContext ctx) {
		// TODO Auto-generated method stub
		return null;
	}
	
	private String convertStreamToString(InputStream is) throws IOException {
		if(is != null) {
		    Writer writer = new StringWriter();

		    char[] buffer = new char[1024];

		    try {
				Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				int n;
				while((n = reader.read(buffer)) != -1) {
				    writer.write(buffer, 0, n);
				}
		    } finally {
		    	is.close();
		    }
		    String returnString = writer.toString();
		    return returnString;
		} else {
		    return "";
		}
    }

}
